package com.sysd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sysd.bean.entity.Concern;
import com.sysd.constant.UserRedisKeyConstant;
import com.sysd.context.UserContext;
import com.sysd.entity.LoginUser;
import com.sysd.exception.ServiceException;
import com.sysd.mapper.ConcernMapper;
import com.sysd.service.ConcernService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 * 关注表 服务实现类
 * </p>
 *
 * @author bsh
 * @since 2025-06-03
 */
@Service
@RequiredArgsConstructor
public class ConcernServiceImpl extends ServiceImpl<ConcernMapper, Concern> implements ConcernService {
    private final ConcernMapper concernMapper;
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 关注
     *
     * @param userId 用户id
     * @return res
     */
    @Override
    public boolean doConcern(Integer userId) {
        LoginUser u1 = UserContext.getLoginUser();
        //如果想自己关注自己，那么就报个异常
        if(userId.equals(u1.getUserId())) {
            throw new ServiceException("不允许自己关注自己!");
        }
        Concern concern = new Concern();
        concern.setUserId(u1.getUserId());
        concern.setConcernUserId(userId);
        return concernMapper.insert(concern) > 0;
    }

    /**
     * 取消关注直接删除掉就好了
     *
     * @param userId id
     * @return res
     */
    @Override
    public boolean cancelConcern(Integer userId) {
        return concernMapper.delete(new QueryWrapper<Concern>().eq("user_id", userId)) > 0;
    }

    /**
     * 关注用户计数
     *
     * @param userId 用户id
     * @return res
     */
    @Override
    public Long concernCount(Integer userId) {
        return stringRedisTemplate.opsForHash().size(String.format(UserRedisKeyConstant.USER_CONCERN_KEY, userId));
    }

    /**
     * 粉丝计数
     *
     * @param userId 用户id
     * @return 结果
     */
    @Override
    public Long fansCount(Integer userId) {
        return stringRedisTemplate.opsForHash().size(String.format(UserRedisKeyConstant.USER_FANS_KEY, userId));
    }
}
